package com.zzyl.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.member.domain.dto.ElderInfoDTO;
import com.zzyl.member.domain.dto.FamilyListDto;
import com.zzyl.member.domain.dto.UserLoginRequestDto;
import com.zzyl.member.domain.pojo.ElderFamilyRelation;
import com.zzyl.member.domain.pojo.FamilyMember;
import com.zzyl.member.domain.vo.UserLoginVo;
import com.zzyl.member.domain.vo.UserVo;
import com.zzyl.member.mapper.FamilyMemberMapper;
import com.zzyl.member.service.IFamilyMemberService;
import com.zzyl.member.service.WechatService;
import com.zzyl.nursing.domain.pojo.Bed;
import com.zzyl.nursing.domain.pojo.Device;
import com.zzyl.nursing.domain.pojo.Elder;
import com.zzyl.nursing.domain.pojo.Room;
import com.zzyl.nursing.mapper.BedMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IElderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author alexis
 * @date 2025-05-26
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {

        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }



    @Autowired
    private TokenService tokenService;
    @Autowired
    private WechatService wechatService;


    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    public UserLoginVo login(UserLoginRequestDto dto) {
        // 1.调用微信api,根据code获取openId
        String openid = wechatService.getOpenid(dto.getCode());
        // 2.根据openId查询用户
        FamilyMember member = this.getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));
        // 4.调用微信api获取用户绑定的手机号
        String phone = wechatService.getPhone(dto.getPhoneCode());
        // 3.如果用户为空，则将openId设置到对象中
        if(ObjectUtil.isNull(member))
        {
            member = FamilyMember.builder().phone(phone).name("先看着").openId(openid).build();
            this.save(member);
        }else {
            if(!phone.equals(member.getPhone()))
            {
                member.setPhone(phone);
                this.updateById(member);
            }
        }

        // 6.将用户id存入token,返回
        Map<String, Object> cliams = MapUtil.<String, Object>builder().put("userId", member.getId()).put("name", member.getName()).build();
        String token = tokenService.createToken(cliams);
        UserLoginVo loginVo = UserLoginVo.builder().token(token).nickName("花开富贵").build();
        return loginVo;
    }

    @Override
    public void geMy() {
        log.info("userId,{}", UserThreadLocal.get());
    }

    @Autowired
    IElderService elderService;
    @Autowired
    DeviceMapper deviceMapper;
    @Autowired
    BedMapper bedMapper;
    @Autowired
    RoomMapper roomMapper;
    @Override
    public List<UserVo> selectlisttionPage(FamilyListDto familyListDto) {
        List<ElderFamilyRelation> familyRelations = familyMemberMapper.getAll(UserThreadLocal.get());
        if (ObjectUtil.isEmpty(familyRelations))
            return null;
        List<UserVo> userVos = new ArrayList<>();
        for (ElderFamilyRelation familyRelation : familyRelations) {
            UserVo userVo = new UserVo();
            userVo.setMid(familyRelation.getFamilyMemberId());
            userVo.setMremark(familyRelation.getRelationType());
            userVo.setElderId(familyRelation.getElderId());
            Elder elder = elderService.selectElderById(familyRelation.getElderId());
            BeanUtil.copyProperties(elder,userVo);
            Device device = deviceMapper.selectOne(Wrappers.lambdaQuery(Device.class).eq(Device::getPhysicalLocationType, -1).eq(Device::getLocationType, 1).eq(Device::getBindingLocation, elder.getId()));
            if(ObjectUtil.isNotEmpty(device)){
                BeanUtil.copyProperties(device,userVo);
            }
            Bed bed = bedMapper.selectBedById(elder.getBedId());
            Room room = roomMapper.selectRoomById(bed.getRoomId());
            userVo.setTypeName(room.getTypeName());
            userVos.add(userVo);
        }
        return userVos;
    }

    @Override
    public void bindFamilyMembers(ElderInfoDTO bindDto) {
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getName, bindDto.getName())
                .eq(Elder::getIdCardNo, bindDto.getIdCard()));
        if (ObjectUtil.isNull(elder)) {
            throw new RuntimeException("老人不存在");
        }
        familyMemberMapper.addFamilyAndElder(elder.getId(), UserThreadLocal.get(), bindDto.getRemark());
    }

//    @Override
//    public UserLoginVo login1(UserLoginRequestDto dto) {
//    // 1.调用微信api,根据code获取openId
//        String openid = wechatService.getOpenid(dto.getCode());
//
//        // 2.根据openId查询用户
//        FamilyMember familyMember1 = familyMemberMapper.selectOne(Wrappers.lambdaQuery(FamilyMember.class).eq(FamilyMember::getOpenId, openid));
//        // 4.调用微信api获取用户绑定的手机号
//        String phone = wechatService.getPhone(dto.getPhoneCode());
//        FamilyMember familyMember = new FamilyMember();
//        // 3.如果用户为空，则将openId设置到对象中
//        if(BeanUtil.isEmpty(familyMember1)) {
//            familyMember.setOpenId(openid);
//            BeanUtil.copyProperties(dto,familyMember);
//            familyMember.setPhone(phone);
//            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
//                    + StringUtils.substring(familyMember.getPhone(), 7));
//            familyMemberService.save(familyMember);
//        }else {
//            if(!familyMember.getPhone().equals(phone))
//                familyMember.setPhone(phone);
//                familyMemberService.updateById(familyMember);
//        }
//
//        Map<String, Object> claims = MapUtil.<String, Object>builder().put("userId", familyMember.getId()).put("name", familyMember.getName()).build();
//
//        UserLoginVo loginVo = new UserLoginVo();
//        loginVo.setToken("asdasdasdasdasdasdasdasdasdasdasd");
//        loginVo.setNickName(familyMember.getName());
//        // 6.将用户id存入token,返回
//        return loginVo;
//    }


}
